package com.cdshangpai.utils.storage;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.http.util.EncodingUtils;

public class FileOpt {
    public Context context;
    public static final String ENCODING = "UTF-8";
    public static String baseFolder="photoapp";

    public FileOpt(Context context)
    {
        this.context=context;
    }

    public String getBaseFolder()
    {
        String path= Environment.getExternalStorageDirectory().getPath()+ File.separator+baseFolder+File.separator;
        File file=new File(path);
        if(!file.exists())
        {
            file.mkdirs();
        }
        return path;
    }

    //创建基础文件目录
    public void createBaseFolder()
    {

    }

    public void writeFileData(String filename, String message){
        try {
            String optFilename=getBaseFolder()+filename;
            FileOutputStream fout = context.openFileOutput(optFilename, context.MODE_PRIVATE);//获得FileOutputStream
            //将要写入的字符串转换为byte数组
            byte[]  bytes = message.getBytes();
            fout.write(bytes);//将byte数组写入文件
            fout.close();//关闭文件输出流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String readFileData(String fileName){
        String result="";
        try {
            String optFilename=getBaseFolder()+fileName;
            FileInputStream fin = context.openFileInput(optFilename);
            //获取文件长度
            int lenght = fin.available();
            byte[] buffer = new byte[lenght];
            fin.read(buffer);
            //将byte数组转换成指定格式的字符串
            result = EncodingUtils.getString(buffer, ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
